import 'package:esc_pos_utils/esc_pos_utils.dart';
import 'package:flutter_pos_printer_platform/flutter_pos_printer_platform.dart';

import '../entity/book_entity.dart';
import '../entity/print_entity.dart';
import '../main.dart';

class Print{

   printing(PrintEntity entity,List<BookEntity> list)  {
    // if(list == null || list.isEmpty){
    //   return;
    // }
    PrinterManager.instance.discovery(type: PrinterType.usb, isBle: false).listen((device) async {
      if(device.name == 'w80'){
        var printerManager = PrinterManager.instance;
        final profile = await CapabilityProfile.load(name: 'XP-N160I');
        // PaperSize.mm80 or PaperSize.mm58
        final generator = Generator(PaperSize.mm80, profile);
        List<int> bytes = [];
        // bytes += generator.setGlobalCodeTable('CP1252');
        // bytes += generator.setStyles(const PosStyles(align: PosAlign.left));
        bytes += generator.text('${settingEntity.deviceName??'轩毅'}(${entity.type==0?'借':'还'}书)',containsChinese: true);
        bytes += generator.feed(2);
        if(entity.type == 0){
          bytes += generator.text('姓名:${entity.uName}',containsChinese: true,);
          bytes += generator.text('读者号:${entity.uid}',containsChinese: true);
        }
        bytes += generator.text('借阅日期:${DateTime.now().toString().substring(0,19)}',containsChinese: true);
        bytes += generator.text('应还日期:${list[0].readyReturnDate}',containsChinese: true);
        bytes += generator.feed(2);
        bytes += generator.text('序号/题名/条码号/结果',containsChinese: true);
        for (int i = 0;i<list.length;i++) {
          bytes += generator.text('${i+1}/《${list[i].mainTitle}》/${list[i].no}/${list[i].state == 1?'成功':'失败'}',containsChinese: true);
        }
        bytes += generator.feed(2);
        bytes += generator.text('此凭条为您的${entity.type==0?'借':'还'}书凭证，请妥善保管',containsChinese: true);
        bytes += generator.feed(4);
        bytes += generator.cut(mode:PosCutMode.partial);
        await printerManager.connect(
            type: PrinterType.usb,
            model: UsbPrinterInput(name: device.name, productId: device.productId, vendorId: device.vendorId));
        await printerManager.send(type: PrinterType.usb, bytes: bytes);
      }
    });

  }
}